﻿using System.IO;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Cfg;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Automapping;
using DataLayer.Types;

namespace DataLayer
{
    public class SessionProvider
    {
        private static string DbFile = "data1.db";
        private static FluentConfiguration _configuration;
        private static ISessionFactory _sessionFactory;

        public static FluentConfiguration Configuration
        {
            get
            {
                if (_configuration == null)
                {
                    log4net.LogManager.GetLogger(typeof(SessionProvider)).Info("Initializing fluent configuration");
                    _configuration = Fluently.Configure()
                        .Database(SQLiteConfiguration.Standard.UsingFile(DbFile))
                        .Mappings(m => m.AutoMappings.Add(
                            AutoMap.AssemblyOf<IBaseRecord>(type => type.Namespace.EndsWith("Types"))
                                .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never()))
                                .ExportTo(@"d:\tmp"))
                        .ExposeConfiguration(BuildSchema);
                }
                return _configuration;
            }
        }

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    _sessionFactory = Configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        private static void BuildSchema(Configuration configuration)
        {
            return; 

            log4net.LogManager.GetLogger(typeof(SessionProvider)).Info("Building schema");
            if (File.Exists(DbFile))
            {
                log4net.LogManager.GetLogger(typeof(SessionProvider)).Info("Deleting existing schema");
                File.Delete(DbFile);
            }

            new SchemaExport(configuration).Create(false, true);
        }

        private SessionProvider() { }

        public static ISession GetSession()
        {
            return SessionFactory.OpenSession();
        }

    }
}